package com.baidu.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("image")
@CrossOrigin
public class ImageCode {
    @Autowired
    private HttpServletResponse response;
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @RequestMapping("code/{uuid}")
    public  void imageCode(@PathVariable String uuid) throws IOException {

        response.addHeader("Cache-Control","no-cache");
        response.addHeader("Cache-Control","no-store");
        response.setContentType("image/jpeg");
        String s = BufferedImageUtils.generateTextCode(BufferedImageUtils.TYPE_ALL_MIXED, 4, null);
        stringRedisTemplate.opsForValue().set(uuid,s,1, TimeUnit.MINUTES);
        BufferedImage bufferedImage = BufferedImageUtils.generateImageCode
                (s, 90, 30, 3, true, Color.white, Color.BLACK, null);
        ImageIO.write(bufferedImage,"jpeg",response.getOutputStream());
    }

}
